﻿using System.Web.Mvc;
using Inscriptionem.Services;

namespace Inscriptionem.MVC
{
    public class LocalizableViewEngine : RazorViewEngine
    {
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            Localization.Language.Current.Value = controllerContext.RouteData.Values["language"] == null ? Localization.Language.Current.Value : controllerContext.RouteData.Values["language"].ToString();

            if (InstallService.IsDBAvailableAndCorrect && !string.IsNullOrWhiteSpace(Localization.Language.Current.Value))
            {
                var result = base.FindView(controllerContext, viewName + "." + Localization.Language.Current.Value, masterName, useCache);

                return result.View == null ? base.FindView(controllerContext, viewName, masterName, useCache) : result;
            }

            return base.FindView(controllerContext, viewName, masterName, useCache);
        }

        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            Localization.Language.Current.Value = controllerContext.RouteData.Values["language"] == null ? Localization.Language.Current.Value : controllerContext.RouteData.Values["language"].ToString();

            if (InstallService.IsDBAvailableAndCorrect && !string.IsNullOrWhiteSpace(Localization.Language.Current.Value))
            {
                var result = base.FindPartialView(controllerContext, partialViewName + "." + Localization.Language.Current.Value, useCache);

                return result.View == null ? base.FindPartialView(controllerContext, partialViewName, useCache) : result;
            }

            return base.FindPartialView(controllerContext, partialViewName, useCache);
        }
    }
}